package com.hand.prantice.ssm.interceptor;

import com.alibaba.fastjson.JSON;
import com.hand.prantice.ssm.annoction.PermissionAnnoction;
import com.hand.prantice.ssm.constant.ErrorMsg;
import com.hand.prantice.ssm.domain.Permission;
import com.hand.prantice.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;


/**
 * @author 马旭阳
 * @date2019/7/17
 */
@Component
public class Controllerinterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isValidate(handler)) {
            Boolean volidate = validateuserPer(request);
            if (volidate) {
                    response.setStatus(200);
                    return true;
            }
        }else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            ErrorMsg errorMsg = new ErrorMsg("not found", "没有权限");
            PrintWriter printWriter = response.getWriter();
            String msgJs = JSON.toJSONString(errorMsg);

            printWriter.print(msgJs);
            printWriter.close();

        }
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("Controllerinterceptor:postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("Controllerinterceptor:afterCompletion");
    }

    private boolean isValidate(Object handler){
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        Annotation methodAnnotation = method.getAnnotation(PermissionAnnoction.class);
        if(!StringUtils.isEmpty(methodAnnotation)) {
                System.out.println("aa");
               return ((PermissionAnnoction) (methodAnnotation)).value();
        }else {
            if (!StringUtils.isEmpty(method.getDeclaringClass().getAnnotation(PermissionAnnoction.class))) {
                return method.getDeclaringClass().getAnnotation(PermissionAnnoction.class).value();
            }
        }
        return false;
    }

    private boolean validateuserPer(HttpServletRequest request) {
        Boolean result = false;
        String userId = request.getHeader("userId");
        if (!StringUtils.isEmpty(userId)) {
            List<Permission> permissionList = userService.queryAll(Long.valueOf(userId));
            String uri = request.getRequestURI();
            String method = request.getMethod();
            AntPathMatcher matcher = new AntPathMatcher();
            for (Permission p : permissionList) {
                if (p.getPath().equals(uri) && p.getMethod().equals(method)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
}
